'use strict';
const cloud = require('wx-server-sdk')
cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV,
})
const request = require('request');
exports.main = async (event, context) => {

	const tokenData = await getWechatAccessToen();
	   return tokenData;

	// const {
	// 	code
	// } = event;
	// const {access_token} = await getWechatAccessToen();
	// const phoneNum = await getPhoneNum(code);
	// return phoneNum;
	// const phoneNum = await cloud.openapi.phonenumber.getPhoneNumber({"code":'',"access_token":''});
	//event为客户端上传的参数
	// console.log('event : ', event)
	// const res = await getPhoneNum(event.code)
};

async function getWechatAccessToen() {
	const AppId = 'wx9265b80566d66341';
	const AppSecret = '2f8d2e24f483c1b92b7f838097afd3c5'
	const tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + AppId + '&' +
		'secret=' + AppSecret;

	const rp = options =>
		new Promise((resolve, reject) => {
			request(options, (error, response, body) => {
				if (error) {
					reject(error);
				}
				resolve(response);
			});
		});
	const result = await rp({
		url: tokenUrl,
		method: 'GET'
	});

	return (typeof result.body === 'object') ? result.body : JSON.parse(result.body);
	// return result;
}

async function getPhoneNum(code) {

	let ACCESS_TOKEN = await getWechatAccessToen();
	let phoneUrl = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' + ACCESS_TOKEN
		.access_token;
	const rp = options =>
		new Promise((resolve, reject) => {
			request(options, (error, response, body) => {
				if (error) {
					reject(error);
				}
				resolve(response);
			});
		});
	
	const result = await rp({
		headers: {
			"content-type": "application/json; charset=UTF-8"
		},
		url: phoneUrl,
		data:{
			"code":code
		},
		method: 'POST'
	});
	return (typeof result.body === 'object') ? result.body : JSON.parse(result.body);
	// return result;
}